<template>
  <div class="new_div1">
    <el-dialog
      draggable
      width="60%"
      title="产品明细列表"
      v-model="dialogVisibles"
      :before-close="shareCancel"
    >
      <div>
        <el-form ref="formQuery" label-width="70px" :model="formList">
          <el-row :gutter="24" justify="space-around">
            <el-col v-bind="layoutCol">
              <div>
                <el-form-item
                  style="width: 100%"
                  label="品牌"
                  prop="assistant_id"
                >
                  <VabSelectForm
                    multiple
                    v-model="formList.assistant_id"
                    :options="assistant_list"
                  />
                </el-form-item>
              </div>
            </el-col>
            <el-col v-bind="layoutCol">
              <div>
                <el-form-item width="160" label="产品条码" prop="barcode">
                  <ProductAllSelect
                    ref="productAllSelectNumberRef"
                    multiple
                    type="barcode"
                    class="width_100"
                    v-model="formList.barcode"
                    :placeholder="'请选择【可粘贴复制快查询】'"
                    :customerNumber="customerNumber"
                    :assistant_id="formList.assistant_id"
                    @pasteNative="pasteNativeSreach"
                  />
                </el-form-item>
              </div>
            </el-col>
            <el-col v-bind="layoutCol">
              <div>
                <el-form-item style="width: 100%" label="产品名称" prop="name">
                  <ProductAllSelect
                    ref="productAllSelectNameRef"
                    multiple
                    type="name"
                    class="width_100"
                    v-model="formList.name"
                    :customerNumber="customerNumber"
                    :assistant_id="formList.assistant_id"
                  />
                </el-form-item>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="24" :lg="24" :xl="24" :span="24">
              <div class="button-query">
                <el-button @click="querySreach" size="small" type="primary">
                  查询
                </el-button>
                <el-button size="small" @click="handleReset">重置</el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div>
        <el-table
          border
          height="320px"
          :data="tableData"
          v-loading="loading"
          style="width: 100%"
          ref="multipleTableRef"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="40" />
          <el-table-column label="序号" align="center" width="80">
            <template #default="scope">
              <span v-text="scope.$index + 1"></span>
            </template>
          </el-table-column>
          <!-- <el-table-column
            empty-text="--"
            label="产品图"
            align="center"
            prop="assistant_name"
            width="100"
          >
            <template #default="{ row }">
              <img
                class="preview_img"
                :src="row.img_url"
                alt=""
                @click="handlePreviewImg(row.img_url)"
              />
            </template>
          </el-table-column> -->
          <el-table-column
            empty-text="--"
            label="品牌"
            align="center"
            prop="assistant_name"
            width="100"
          >
            <template #default="scope">
              <span
                class="ellipsis"
                v-text="_FieldFormat(scope.row.assistant_name, '')"
              ></span>
            </template>
          </el-table-column>
          <el-table-column
            empty-text="--"
            label="产品条码"
            prop="barcode"
            align="center"
            width="160"
          >
            <template #default="scope">
              <span
                class="ellipsis"
                v-text="_FieldFormat(scope.row.barcode, '')"
              ></span>
            </template>
          </el-table-column>
          <el-table-column
            empty-text="--"
            label=" 产品名称"
            prop="name"
            align="center"
            min-width="100"
          >
            <template #default="scope">
              <span
                class="ellipsis"
                v-text="_FieldFormat(scope.row.name, '')"
              ></span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer customerDialog3">
          <el-button type="primary" size="small" @click="share_save">
            确定
          </el-button>
          <el-button size="small" @click="shareCancel">返回</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 图片预览 -->
    <VabPreviewImg ref="vabPreviewImgRef" />
  </div>
</template>

<script setup lang="ts">
  import lodash from 'lodash'
  import { ElMessage } from 'element-plus'
  import { FieldFormat } from '/@/utils/utils'
  import ProductAllSelect from './ProductAllSelect.vue'
  import {
    getHomeProductSearch,
    getCustomerProductList,
    homeProductSearchClass,
  } from '~/src/api/dms/home/homeCustomer'
  defineOptions({
    name: 'ProductsAll',
  })

  const layoutCol = {
    xs: 24,
    sm: 12,
    md: 8,
    lg: 8,
    xl: 8,
    span: 8,
  }

  const productAllSelectNameRef = ref()
  const productAllSelectNumberRef = ref()

  const props = defineProps(['customerNumber'])

  const _FieldFormat = (value: string, type = '') => {
    return FieldFormat(value, type)
  }
  const dialogVisibles = ref(false)
  const formQuery = ref<any>(null)
  const loading = ref(false)
  const formList = ref<any>({
    assistant_id: [],
    name: [],
    number: '',
    barcode: '',
    class_id1: [],
    class_id2: [],
  })
  const tableData = ref<any>([])
  // *********查询***************
  const assistant_list = ref([])
  const name_list = ref([])
  const number_list = ref([])
  const class_id1_list = ref([])
  const class_id2_list = ref<any>([])
  const all_date = ref<any>([])
  const class_date = ref(undefined)

  const page = ref(1)
  const count = ref(0)
  const isPaste = ref(false)

  const vabPreviewImgRef = ref()

  //多选
  let multipleDate = reactive<any>([])
  let multipleList = ref<any>(undefined)
  const handleSelectionChange = (val: any, va: any) => {
    multipleDate = val
  }
  const multipleTableRef = ref()

  /**
   * @method
   */

  const emit = defineEmits(['handleShareSave'])

  const share_save = (va: any) => {
    multipleList.value = [...multipleDate]
    emit(
      'handleShareSave',
      multipleDate.map((item: any) => {
        return {
          ...item,
          goods_type: '正品',
        }
      })
    )
    dialogVisibles.value = false
  }
  const shareCancel = () => {
    multipleDate = []
    dialogVisibles.value = false
  }
  const watchScroll = lodash.debounce(() => {
    multipleTableRef.value.$refs.bodyWrapper.addEventListener(
      'scroll',
      async (res: any) => {
        const { clientHeight, scrollTop, scrollHeight } = res.target
        if (clientHeight + scrollTop === scrollHeight) {
          if (page.value * 20 < count.value) {
            await page.value++
          } else {
            ElMessage.success('到底了~')
            return
          }
          loading.value = true
          _GetProductList(3)
        }
      },
      true
    )
  }, 1000)

  watchEffect(() => {
    assistant_list.value = all_date.value.brand?.map((i: any) => {
      return { value: i.entry_id, label: i.name }
    })
    number_list.value = all_date.value.number?.map((i: any) => {
      return { value: i.number }
    })
    name_list.value = all_date.value.name?.map((i: any) => {
      return { value: i.name, label: i.name }
    })
    class_id1_list.value = all_date.value.class_one?.map((i: any) => {
      return { value: i.id, label: i.data_title }
    })
  })
  watch(class_date, () => {
    if (class_date) {
      class_id2_list.value = class_date.value
    }
  })
  const _GetProductSearch = async () => {
    try {
      const res = await getHomeProductSearch({})
      res.data.brand.push({ entry_id: '', name: '空' })
      res.data.class_one.push({ id: '', data_title: '空' })
      res.data.class_two.push({ id: '', data_title: '空' })
      res.data.series.push({ id: '', data_title: '空' })
      res.data.category.push({ id: '', data_title: '空' })
      all_date.value = res.data
    } catch (error) {}
  }
  // 二级分类
  const _ProductSearchClass = async (class_id: any) => {
    class_id2_list.value = []
    try {
      const res = await homeProductSearchClass({ class_id })
      class_id2_list.value = res.data.map((item: any) => {
        return {
          value: item.id,
          label: item.data_title,
        }
      })
    } catch (error) {}
  }
  const querySreach = lodash.debounce(async (va: any) => {
    loading.value = true
    tableData.value = []
    page.value = 1
    await _GetProductList(1)
  }, 500)
  const handleReset = lodash.debounce(async (va: any) => {
    if (formQuery.value) formQuery.value.resetFields()
    loading.value = true
    tableData.value = []
    page.value = 1
    if (productAllSelectNumberRef.value)
      productAllSelectNumberRef.value.loadDataList()
    if (productAllSelectNameRef.value)
      productAllSelectNameRef.value.loadDataList()
    _GetProductList(2)
  }, 500)
  const _GetProductList = async (type = 0) => {
    if (!props.customerNumber) return

    let data = {
      page: page.value,
      limit: 20,
      type: 1,
      customer_number: props.customerNumber,
      filter: { ...formList.value },
    }

    try {
      let res = await getCustomerProductList({ ...data })

      tableData.value = [...tableData.value, ...res.data.list]
      count.value = res.data.count

      if (type == 1) ElMessage.success('查询成功')
      if (type == 2) ElMessage.success('重置成功')
      // if (type == 3) ElMessage.success('加载成功')

      loading.value = false
    } catch (error) {}
  }

  // 筛选品牌更新产品
  const vabSelectFormAssistant = (value: any) => {
    productAllSelectNumberRef.value.loadDataList(value)
    productAllSelectNameRef.value.loadDataList(value)
  }

  // 预览图片
  const handlePreviewImg = (file = '') => {
    vabPreviewImgRef.value.open(file)
  }

  // 快粘贴筛选
  const pasteNativeSreach = async ({ options, type }: any) => {
    formList.value[type] = options
    tableData.value = []
    if (!options.length) return //黏贴值为空 即列表为空

    loading.value = true
    page.value = 1
    await _GetProductList(1)
    // 表格全选
    multipleTableRef.value.toggleAllSelection()
  }

  // 打开弹窗
  const open = () => {
    dialogVisibles.value = true
    tableData.value = []
    formList.value = {}
    _GetProductSearch()
    _GetProductList()
  }

  /**
   * @实例
   */

  watchEffect(() => {
    if (multipleTableRef.value) watchScroll()
  })

  //抛出数据
  defineExpose({
    dialogVisibles,
    multipleList,
    handleReset,
    open,
  })
</script>

<style lang="scss" scoped>
  .new_div1 {
    :deep() {
      .el-dialog__body {
        padding-top: 10px;
      }
    }
  }

  .customerDialog3 {
    display: flex;
    justify-content: center;
  }

  .button-query {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    height: 100%;
    padding-bottom: 12px;
  }
</style>
